package Soligee.report;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import javax.xml.parsers.ParserConfigurationException;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.xml.sax.SAXException;

public class Relatorio {

   public void geraRelatorioPDF (String relatorioNome) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException, JRException, SQLException{
        this.geraJrprint (relatorioNome);
        //gera PDF
        String jrprint = relatorioNome + ".jrprint";
        String pdf = relatorioNome + ".pdf";
        File file = new File(jrprint);
        JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(file);
        JRPdfExporter pdfExporter = new JRPdfExporter();

        pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,pdf);
        pdfExporter.exportReport();



        //JasperExportManager.exportReportToHtmlFile(jrprint);
        //gera vizualização do PDF
        //JasperViewer.viewReport(jasperPrint);



    }

    public void geraJrprint (String relatorioNome) throws JRException, ClassNotFoundException, SQLException{
        //Compila .jrxml e gera um .jasper
        JasperCompileManager.compileReportToFile(relatorioNome + ".jrxml");
        //Cria uma conexao com o banco
        Connection connection = null;
        Class.forName("org.postgresql.Driver");
        String db = "jdbc:postgresql://localhost:5432/Soligee";
        connection = (Connection) DriverManager.getConnection(db,"postgres","admin");
        //Criar arquivo .jrprint
        String jasper = relatorioNome + ".jasper";
        JasperFillManager.fillReportToFile(jasper,new HashMap(), connection);
    }
}